package com.osfw.system.service.manage.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osfw.framework.constants.Constants;
import com.osfw.framework.constants.UserConstants;
import com.osfw.framework.core.domain.Ztree;
import com.osfw.framework.exception.ServiceException;
import com.osfw.framework.utils.StringUtils;
import com.osfw.framework.utils.spring.SpringUtils;
import com.osfw.framework.utils.text.Convert;
import com.osfw.system.entity.manage.SysDept;
import com.osfw.system.entity.manage.SysMenu;
import com.osfw.system.entity.manage.SysRole;
import com.osfw.system.entity.manage.SysUser;
import com.osfw.system.mapper.manage.SysDeptMapper;
import com.osfw.system.mapper.manage.SysUserMapper;
import com.osfw.system.service.manage.ISysDeptService;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 部门管理 服务实现
 */
@Service
public class SysDeptServiceImpl extends ServiceImpl<SysDeptMapper, SysDept> implements ISysDeptService {
    @Resource
    private SysDeptMapper deptMapper;
    @Resource
    private SysUserMapper userMapper;


    /**
     * 查询组织机构内设部门信息（有组织机构信息）
     *
     * @param deptId 组织机构内设部门信息ID
     * @return 组织机构内设部门信息
     */
    @Override
    public SysDept selectDeptById(Long deptId) {
        SysDept sysDept = new SysDept();
        sysDept.setDeptId(deptId);
        return deptMapper.selectSysDeptById(sysDept);
    }

    /**
     * 查询部门管理数据
     *
     * @param dept 部门信息
     * @return 部门信息集合
     */
    @Override
    public List<SysDept> selectDeptList(SysDept dept) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysDept::getDeptId);
        queryWrapper.eq(dept.getDeptId() != null && dept.getDeptId().longValue() != 0l, SysDept::getDeptId, dept.getDeptId());
        queryWrapper.eq(dept.getParentId() != null && dept.getDeptId().longValue() != 0l, SysDept::getParentId, dept.getParentId());
        queryWrapper.like(StringUtils.isNotEmpty(dept.getDeptName()), SysDept::getDeptName, dept.getDeptName());
        queryWrapper.eq(StringUtils.isNotEmpty(dept.getStatus()), SysDept::getStatus, dept.getStatus());
        List<SysDept> list = list(queryWrapper);
        List<Long> deptIds = list.stream().map(x -> x.getDeptId()).collect(Collectors.toList());
        if (!deptIds.isEmpty()) {
            LambdaQueryWrapper<SysDept> queryWrapper2 = new LambdaQueryWrapper<>();
            queryWrapper2.orderByAsc(SysDept::getAncestors, SysDept::getOrderNum);
            List<SysDept> allList = list(queryWrapper2);
            allList = allList.stream().filter(x -> {
                boolean res = false;
                if (deptIds.contains(x.getDeptId())) {
                    res = true;
                } else {
                    long count = deptIds.stream().filter(deptId -> StringUtils.str2Set(x.getAncestors(), ",").contains(deptId + "")).count();
                    res = count == 0 ? false : true;
                }
                return res;
            }).collect(Collectors.toList());
            return allList;
        }
        return Collections.EMPTY_LIST;
    }

    /**
     * 查询部门管理数据（直属下级部门）
     *
     * @param dept 部门信息
     * @param user 登录用户
     * @return 部门信息集合
     */
    @Override
    public List<SysDept> selectImmediateChildrenDeptList(SysDept dept, SysUser user) {
        List<SysDept> deptList;
        if (dept.getParentId() == null && dept.getDeptName() == null && dept.getStatus() == null) {
            dept.setParentId(0l);
        }
        if (user.isAdmin()) {
            deptList = deptMapper.selectImmediateChildrenDeptList(dept);
        } else {
            dept.getParams().put("userId", user.getUserId());
            deptList = deptMapper.selectImmediateChildrenDeptListByUserId(dept);
        }
        return deptList;
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    public List<Ztree> selectDeptTree(SysDept dept) {
        List<SysDept> deptList = selectDeptList(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    /**
     * 查询部门管理树
     *
     * @param dept 部门信息
     * @return 所有部门信息
     */
    @Override
    public List<Ztree> selectDeptTreeWithCount(SysDept dept) {
        List<SysDept> deptList = deptMapper.selectDeptTreeWithCount(dept);
        List<Ztree> ztrees = initZtree(deptList);
        return ztrees;
    }

    @Override
    public List<Ztree> deptTreeDataImmediateChild(SysUser user, SysDept dept) {
        if (dept != null && dept.getParentId() == null) {
            dept.setParentId(0l);
        }
        List<SysDept> menuList = selectImmediateChildrenDeptList(dept, user);
        List<Ztree> ztrees = initZtree(menuList);
        return ztrees;
    }

    /**
     * 查询部门管理树（排除下级）
     *
     * @param dept 部门
     * @return 所有部门信息
     */
    @Override
    public List<Ztree> selectDeptTreeExcludeChild(SysDept dept) {
        Long excludeId = dept.getExcludeId();
        List<SysDept> depts = selectDeptList(dept);
        if (excludeId.intValue() > 0) {
            depts.removeIf(d -> d.getDeptId().intValue() == excludeId || ArrayUtils.contains(StringUtils.split(d.getAncestors(), ","), excludeId + ""));
        }
        List<Ztree> ztrees = initZtree(depts);
        return ztrees;
    }

    /**
     * 根据角色ID查询部门（数据权限）
     *
     * @param role 角色对象
     * @return 部门列表（数据权限）
     */
    @Override
    public List<Ztree> roleDeptTreeData(SysRole role) {
        Long roleId = role.getRoleId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<SysDept> deptList = list();
        if (StringUtils.isNotNull(roleId)) {
            List<String> roleDeptList = deptMapper.selectRoleDeptTree(roleId);
            ztrees = initZtree(deptList, roleDeptList);
        } else {
            ztrees = initZtree(deptList);
        }
        return ztrees;
    }

    /**
     * 对象转部门树
     *
     * @param deptList 部门列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList) {
        return initZtree(deptList, null);
    }

    /**
     * 对象转部门树
     *
     * @param deptList     部门列表
     * @param roleDeptList 角色已存在菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<SysDept> deptList, List<String> roleDeptList) {

        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleDeptList);
        for (SysDept dept : deptList) {
            if (UserConstants.DEPT_NORMAL.equals(dept.getStatus())) {
                Ztree ztree = new Ztree();
                ztree.setId(dept.getDeptId());
                ztree.setpId(dept.getParentId());
                if (dept.getUserCount() != null) {
                    ztree.setName(dept.getDeptName() + "（" + dept.getUserCount() + "人）");
                } else {
                    ztree.setName(dept.getDeptName());
                }
                ztree.setTitle(dept.getDeptName());
                // 是否父节点
                ztree.setIsParent("1".equals(dept.getIsParent()) ? "true" : "false");
                if (isCheck) {
                    ztree.setChecked(roleDeptList.contains(dept.getDeptId() + dept.getDeptName()));
                }
                ztrees.add(ztree);
            }
        }
        return ztrees;
    }

    /**
     * 根据父部门ID查询下级部门数量
     *
     * @param parentId 部门ID
     * @return 结果
     */
    @Override
    public int selectDeptCount(Long parentId) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDept::getDelFlag, "0").eq(SysDept::getParentId, parentId);
        return count(queryWrapper);
    }

    /**
     * 查询部门是否存在用户
     *
     * @param deptId 部门ID
     * @return 结果 true 存在 false 不存在
     */
    @Override
    public boolean checkDeptExistUser(Long deptId) {
        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getDelFlag, "0").eq(SysUser::getDeptId, deptId);
        int result = userMapper.selectCount(queryWrapper);
        return result > 0;
    }

    /**
     * 删除部门管理信息
     *
     * @param deptId 部门ID
     * @return 结果
     */
    @Override
    @Transactional
    public boolean deleteDeptById(Long deptId) {
        SysDept old_dept = selectDeptById(deptId);
        int count = selectDeptCount(old_dept.getParentId());
        if (count == 1) {
            SysDept parentDept = new SysDept();
            parentDept.setDeptId(old_dept.getParentId());
            parentDept.setIsParent("0");
            updateById(parentDept);
        }
        return removeById(deptId);
    }

    /**
     * 新增保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean insertDept(SysDept dept) {
        SysDept info = getById(dept.getParentId());
        // 如果父节点不为"正常"状态,则不允许新增子节点
        if (info != null && !UserConstants.DEPT_NORMAL.equals(info.getStatus())) {
            throw new ServiceException("部门停用，不允许新增");
        }
        int count = selectDeptCount(dept.getParentId());
        if (count == 0) {
            SysDept parentDept = new SysDept();
            parentDept.setDeptId(dept.getParentId());
            parentDept.setIsParent("1");
            updateById(parentDept);
        }
        dept.setIsParent("0");
        dept.setAncestors((info == null || info.getAncestors() == null ? "" : info.getAncestors()) + "," + dept.getParentId());
        return save(dept);
    }

    /**
     * 修改保存部门信息
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    @Transactional
    public boolean updateDept(SysDept dept) {
        SysDept newParentDept = getById(dept.getParentId());
        SysDept oldDept = selectDeptById(dept.getDeptId());
        if (StringUtils.isNotNull(newParentDept) && StringUtils.isNotNull(oldDept)) {
            String newAncestors = newParentDept.getAncestors() + "," + newParentDept.getDeptId();
            String oldAncestors = oldDept.getAncestors();
            dept.setAncestors(newAncestors);
            updateDeptChildren(dept.getDeptId(), newAncestors, oldAncestors);
        }
        if (oldDept.getParentId().longValue() != dept.getParentId().longValue()) {
            int old_count = selectDeptCount(oldDept.getParentId());
            if (old_count == 1) {
                SysDept parentMenu = new SysDept();
                parentMenu.setDeptId(oldDept.getParentId());
                parentMenu.setIsParent("0");
                updateById(parentMenu);
            }
            int count = selectDeptCount(dept.getParentId());
            if (count == 0) {
                SysDept parentMenu = new SysDept();
                parentMenu.setDeptId(dept.getParentId());
                parentMenu.setIsParent("1");
                updateById(parentMenu);
            }
        }
        boolean result = updateById(dept);
        if (UserConstants.DEPT_NORMAL.equals(dept.getStatus()) && StringUtils.isNotEmpty(dept.getAncestors())
                && !StringUtils.equals("0", dept.getAncestors())) {
            // 如果该部门是启用状态，则启用该部门的所有上级部门
            updateParentDeptStatusNormal(dept);
        }
        return result;
    }

    /**
     * 修改该部门的父级部门状态
     *
     * @param dept 当前部门
     */
    private void updateParentDeptStatusNormal(SysDept dept) {
        lambdaUpdate()
                .set(SysDept::getStatus, "0")
                .in(SysDept::getDeptId, Convert.toLongArray(dept.getAncestors()))
                .update();
    }

    /**
     * 修改子元素关系
     *
     * @param deptId       被修改的部门ID
     * @param newAncestors 新的父ID集合
     * @param oldAncestors 旧的父ID集合
     */
    private void updateDeptChildren(Long deptId, String newAncestors, String oldAncestors) {
        List<SysDept> children = list().stream().filter(x -> StringUtils.str2Set(x.getAncestors(), ",").contains(deptId)).collect(Collectors.toList());
        for (SysDept child : children) {
            child.setAncestors(child.getAncestors().replaceFirst(oldAncestors, newAncestors));
        }
        if (children.size() > 0) {
            updateBatchById(children);
        }
    }

    /**
     * 根据ID查询所有子部门（正常状态）
     *
     * @param deptId 部门ID
     * @return 子部门数
     */
    @Override
    public long selectNormalChildrenDeptCountById(Long deptId) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysDept::getDeptId, SysDept::getAncestors);
        queryWrapper.eq(SysDept::getStatus, 0).eq(SysDept::getDelFlag, "0");
        return list(queryWrapper).stream()
                .filter(x -> StringUtils.str2Set(x.getAncestors(), ",").contains(deptId))
                .count();
    }

    @Override
    public List<Long> selectNormalChildrenDeptIdById(Long deptId) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.select(SysDept::getDeptId, SysDept::getAncestors);
        queryWrapper.eq(SysDept::getStatus, 0).eq(SysDept::getDelFlag, "0");
        return list(queryWrapper).stream()
                .filter(x -> StringUtils.str2Set(x.getAncestors(), ",").contains(deptId))
                .map(x -> x.getDeptId()).collect(Collectors.toList());
    }

    @Override
    public List<SysDept> selectNormalChildrenDeptById(Long deptId) {
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDept::getStatus, 0).eq(SysDept::getDelFlag, "0");
        return list(queryWrapper).stream()
                .filter(x -> StringUtils.str2Set(x.getAncestors(), ",").contains(deptId))
                .collect(Collectors.toList());
    }

    /**
     * 校验部门名称是否唯一
     *
     * @param dept 部门信息
     * @return 结果
     */
    @Override
    public String checkDeptNameUnique(SysDept dept) {
        Long deptId = StringUtils.isNull(dept.getDeptId()) ? -1L : dept.getDeptId();
        LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysDept::getDeptName, dept.getDeptName())
                .eq(SysDept::getParentId, dept.getParentId())
                .eq(SysDept::getDelFlag, "0");
        List<SysDept> depts = list(queryWrapper);
        if (depts != null && !depts.isEmpty()) {
            if (StringUtils.isNotNull(depts.get(0)) && depts.get(0).getDeptId().longValue() != deptId.longValue()) {
                return Constants.NOT_UNIQUE;
            }
        }
        return Constants.UNIQUE;
    }

    /**
     * 校验部门是否有数据权限
     *
     * @param deptId 部门id
     */
    @Override
    public void checkDeptDataScope(Long deptId) {
        if (!SysUser.isAdmin(StpUtil.getLoginIdAsLong()) && StringUtils.isNotNull(deptId)) {
            SysDept dept = new SysDept();
            dept.setDeptId(deptId);
            List<SysDept> depts = SpringUtils.getAopProxy(this).selectDeptList(dept);
            if (StringUtils.isEmpty(depts)) {
                throw new ServiceException("没有权限访问部门数据！");
            }
        }
    }

    /**
     * 查询部门用户
     *
     * @param deptIds 部门ID
     * @param isLeader 是否仅查询直属领导（0-否，1-是）
     */
    @Override
    public List<SysUser> selectDeptUserByProc(List<Long> deptIds, Integer isLeader) {
        if (deptIds.isEmpty()) {
            return new ArrayList<>();
        }
        if (isLeader.intValue() == Constants.YES_INTEGER.intValue()) {
            LambdaQueryWrapper<SysDept> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SysDept::getDeptId, deptIds);
            List<SysDept> depts = list(queryWrapper);
            if (!depts.isEmpty()) {
                List<Long> leaderIds = depts.stream().map(x -> x.getLeader()).collect(Collectors.toList());
                if (!leaderIds.isEmpty()) {
                    LambdaQueryWrapper<SysUser> userQueryWrapper = new LambdaQueryWrapper<>();
                    userQueryWrapper.in(SysUser::getUserId, leaderIds);
                    return userMapper.selectList(userQueryWrapper);
                }
            }
        } else {
            LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SysUser::getDeptId, deptIds);
            return userMapper.selectList(queryWrapper);
        }
        return new ArrayList<>();
    }

}
